package com.comecrd.service.impl;

import com.comecrd.model.CheckIn;
import com.comecrd.model.dto.CheckInDTO;
import com.comecrd.model.dto.UserDTO;
import com.comecrd.repository.CheckInMapper;
import com.comecrd.service.CheckInService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.comecrd.model.dto.ImageDTO;

@Service
public class CheckInServiceImpl implements CheckInService {
    
    @Autowired
    private CheckInMapper checkInMapper;
    
    @Override
    @Transactional
    public CheckIn saveCheckIn(CheckIn checkIn) {
        checkInMapper.insert(checkIn);
        return checkIn;
    }
    
    @Override
    public CheckInDTO findById(Long id, Long currentUserId) {
        return checkInMapper.selectById(id, currentUserId);
    }
    
    @Override
    public List<CheckInDTO> findByUserId(Long userId, Long currentUserId, int page, int size) {
        int offset = (page - 1) * size;
        return checkInMapper.selectByUserId(userId, currentUserId, offset, size);
    }
    
    @Override
    public List<CheckInDTO> findAll(Long currentUserId, int page, int size) {
        // 回到原始的selectList方法调用
        int offset = (page - 1) * size;
        return checkInMapper.selectList(currentUserId, offset, size);
    }
    
    @Override
    @Transactional
    public void deleteById(Long id) {
        // MyBatis中可以通过配置级联删除或者在事务中执行多个删除操作
        // 这里假设数据库中已经设置了外键级联删除
        checkInMapper.deleteById(id);
    }
    
    @Override
    public CheckInDTO convertToDTO(CheckIn checkIn, Long currentUserId) {
        // 由于MyBatis已经在SQL中直接返回了DTO对象，这个方法可能不再需要
        // 但为了保持接口兼容性，这里简单实现
        CheckInDTO dto = new CheckInDTO();
        dto.setId(checkIn.getId());
        dto.setContent(checkIn.getContent());
        // 将字符串URL列表转换为ImageDTO对象列表
        List<String> imageUrls = checkIn.getImageUrls();
        if (imageUrls != null) {
            List<ImageDTO> images = imageUrls.stream()
                .map(url -> {
                    ImageDTO imageDTO = new ImageDTO();
                    imageDTO.setUrl(url);
                    return imageDTO;
                })
                .collect(Collectors.toList());
            dto.setImages(images);
        } else {
            dto.setImages(new ArrayList<>());
        }
        // 使用setLocationName代替setLocation
        dto.setLocationName(checkIn.getLocationName());
        dto.setLatitude(checkIn.getLatitude());
        dto.setLongitude(checkIn.getLongitude());
        // 使用setCreatedAt代替setCreateTime
        dto.setCreatedAt(checkIn.getCreatedAt());
        return dto;
    }
    
    @Override
    public List<CheckInDTO> convertToDTOList(List<CheckIn> checkIns, Long currentUserId) {
        return checkIns.stream()
                .map(checkIn -> convertToDTO(checkIn, currentUserId))
                .collect(Collectors.toList());
    }
    
    @Override
    public CheckInService.UserStats getUserStats(Long userId) {
        Integer checkInCount = checkInMapper.countByUserId(userId);
        Integer likeCount = checkInMapper.sumLikesByUserId(userId);
        // 评论数暂时设为0，实际应该从CommentMapper查询
        int commentCount = 0;
        return new CheckInService.UserStats(
            checkInCount != null ? checkInCount : 0, 
            likeCount != null ? likeCount : 0, 
            commentCount);
    }
    
    @Override
    @Transactional
    public Map<String, Object> toggleLike(Long checkInId, Long userId) {
        Map<String, Long> params = new HashMap<>();
        params.put("checkInId", checkInId);
        params.put("userId", userId);
        
        // 检查当前点赞状态
        Integer liked = checkInMapper.checkLikeStatus(params);
        boolean isLiked = liked != null && liked > 0;
        
        if (isLiked) {
            // 取消点赞
            checkInMapper.unlikeCheckIn(params);
        } else {
            // 点赞
            checkInMapper.likeCheckIn(params);
        }
        
        // 重新查询点赞状态和数量
        CheckInDTO checkInDTO = checkInMapper.selectById(checkInId, userId);
        Map<String, Object> result = new HashMap<>();
        result.put("isLiked", !isLiked);
        result.put("likeCount", checkInDTO != null ? checkInDTO.getLikeCount() : 0);
        
        return result;
    }
    

}